import axios from 'axios'
import store from '@/store'
import { isCheckTimeout } from '@/utils/auth'
import { ElMessage } from 'element-plus'

const service = axios.create({
  timeout: 1000,
  baseURL: process.env.VUE_APP_BASE_API
})
// 请求拦截器
service.interceptors.request.use((config) => {
// 添加 icode
  config.headers.icode = 'B86023497D0D1662'
  if (store.getters.token) {
    if (isCheckTimeout()) {
      store.dispatch('user/loginOut')
      return Promise.reject(new Error('token 失效'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  // 必须返回 config
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
  return response
}, error => {
  // 判断token是否失效
  if (error.response && error.response.data && error.response.data.code === 401) {
    store.dispatch('user/loginOut')
  }
  ElMessage.error(error.message)
  return Promise.reject(error)
})

export default service
